package com.molyfun.parents.im;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.BaseChoosePicActivity;
import com.molyfun.parents.activity.common.attachment.AttachmentView;
import com.molyfun.parents.activity.common.attachment.AttachmentViewer;
import com.molyfun.parents.fragment.dialog.CommonInputDialogFragment;
import com.molyfun.parents.rest.BaseResponse;
import com.molyfun.parents.rest.bean.CustomPlanDocListResponse;
import com.molyfun.parents.rest.bean.CustomPlanFileUploadRequest;
import com.molyfun.parents.rest.bean.CustomPlanlistResponse;
import com.molyfun.parents.rest.bean.MediaobjectlistBean;
import com.molyfun.parents.uievent.EventDispatcherEnum;
import com.molyfun.parents.view.common.MfEditText;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.molyfun.parents.im.ConsultActivity.FLAG_PLAN_LIST_BEAN;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:09/10/2017.
 */

public class CustomPlanFileUploadActivity extends BaseChoosePicActivity implements View.OnClickListener {

    @InjectView(R.id.base_title_left)
    ImageView mBaseTitleLeft;
    @InjectView(R.id.base_title)
    TextView mTitle;
    @InjectView(R.id.commit)
    TextView mCommit;
    @InjectView(R.id.file_upload_list)
    LinearLayout mFIleUploadList;
    @InjectView(R.id.empty_layout)
    LinearLayout mEmptyLayout;

    private int mCurrentUploadPosition = 0;

    private List<UploadCustomPlanViewHolder> mUploadCustomPlanList;

    protected CustomPlanlistResponse.PlanListBean mPlanListBean;
    private List<CustomPlanDocListResponse.DocListBean> mDataList;

    private boolean isEdited = true;

    public static final void startActivity(Context context, CustomPlanlistResponse.PlanListBean planListBean) {
        Intent intent = new Intent();
        intent.setClass(context, CustomPlanFileUploadActivity.class);
        intent.putExtra(FLAG_PLAN_LIST_BEAN, planListBean);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_plan_file_upload);
//        AndroidBug5497Workaround.assistActivity(this);
        ButterKnife.inject(this);
        getSupportActionBar().setTitle("");
        mBaseTitleLeft.setOnClickListener(this);
        mCommit.setOnClickListener(this);
        mTitle.setText("上传资料");

        mPlanListBean = getIntent().getParcelableExtra(FLAG_PLAN_LIST_BEAN);

        if (TextUtils.isEmpty(mPlanListBean.getDegree()) || !mPlanListBean.getDegree().equals("-1")) {
            isEdited = false;
            mCommit.setVisibility(View.GONE);
        }

        if (mPlanListBean != null) {
            initData();
        } else {
            mEmptyLayout.setVisibility(View.VISIBLE);
        }

    }

    private void initData() {
        Call<CustomPlanDocListResponse> call = MFPApplication.getInstance().getRestClient().getCustomPlanDocList(mPlanListBean.getId());
        call.enqueue(new Callback<CustomPlanDocListResponse>() {
            @Override
            public void onResponse(Call<CustomPlanDocListResponse> call, Response<CustomPlanDocListResponse> response) {
                dismissProgressDialog();
                if (response.body().getData() != null && response.body().getData().size() > 0) {
                    mEmptyLayout.setVisibility(View.GONE);
                    mDataList = response.body().getData();
                    mUploadCustomPlanList = new ArrayList<UploadCustomPlanViewHolder>(response.body().getData().size());
                    int lineCount = 0;
                    mFIleUploadList.removeAllViews();
                    for (final CustomPlanDocListResponse.DocListBean docListBean : response.body().getData()) {
                        final int currentLine = lineCount;
                        //TODO 添加数据到列表
                        if (!CustomPlanFileUploadActivity.this.isFinishing()) {
                            if (isEdited) {
                                View view = LayoutInflater.from(CustomPlanFileUploadActivity.this).inflate(R.layout.layout_custom_plan_file_upload_item, null, false);
                                TextView uploadTitle = (TextView) view.findViewById(R.id.plan_file_title);
                                uploadTitle.setText(docListBean.getName());
                                AttachmentView attachmentView = (AttachmentView) view.findViewById(R.id.attachmentview);
                                attachmentView.addList(docListBean.getMediaobjectlist());
                                attachmentView.setAttachmentAddCallback(new AttachmentView.AttachmentAddCallback() {
                                    @Override
                                    public void onAttachmentAdd() {
                                        mCurrentUploadPosition = currentLine;
                                        chooseMedia();
                                    }
                                });
                                attachmentView.setAttachmentDelCallback(new AttachmentView.AttachmentDelCallback() {
                                    @Override
                                    public void onAttachmentDel(MediaobjectlistBean mediaobjectlistBean) {
                                        mDataList.get(mCurrentUploadPosition).setMediaobjectlist(mUploadCustomPlanList.get(mCurrentUploadPosition).getmAttachmentView().getAttachment());
                                    }
                                });
                                final TextView mfEditText = (TextView) view.findViewById(R.id.mfedittext);
                                mfEditText.setText(docListBean.getContent());

                                mfEditText.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        new CommonInputDialogFragment.CommonInputDialogBuilder(docListBean.getContent())
                                                .setOnCommonInputCallback(new CommonInputDialogFragment.OnCommonInputCallback() {
                                                    @Override
                                                    public void onInputConfirm(String content) {
                                                        mfEditText.setText(content);
                                                        mDataList.get(currentLine).setContent(content);
                                                    }
                                                })
                                                .build(getSupportFragmentManager().beginTransaction());
                                    }
                                });

//                                mfEditText.addTextChangedListener(new TextWatcher() {
//                                    @Override
//                                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//                                    }
//
//                                    @Override
//                                    public void onTextChanged(CharSequence s, int start, int before, int count) {
//                                    }
//
//                                    @Override
//                                    public void afterTextChanged(Editable s) {
//                                        mDataList.get(currentLine).setContent(s.toString());
//                                    }
//                                });
                                mFIleUploadList.addView(view);
                                mUploadCustomPlanList.add(new UploadCustomPlanViewHolder(attachmentView, mfEditText));
                            } else {
                                View view = LayoutInflater.from(CustomPlanFileUploadActivity.this).inflate(R.layout.layout_custom_plan_file_upload_item_unedited, null, false);
                                TextView uploadTitle = (TextView) view.findViewById(R.id.plan_file_title);
                                uploadTitle.setText(docListBean.getName());
                                AttachmentViewer attachmentView = (AttachmentViewer) view.findViewById(R.id.attachmentviewer);
                                if (docListBean.getMediaobjectlist() == null || docListBean.getMediaobjectlist().size() == 0) {
                                    attachmentView.setVisibility(View.GONE);
                                } else {
                                    attachmentView.setVisibility(View.VISIBLE);
                                    attachmentView.initData(docListBean.getMediaobjectlist());
                                }

                                TextView mfEditText = (TextView) view.findViewById(R.id.content);
                                mfEditText.setText(docListBean.getContent());
                                mFIleUploadList.addView(view);
                            }


                        }
                        lineCount++;

                    }
                }else {
                    mEmptyLayout.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailure(Call<CustomPlanDocListResponse> call, Throwable t) {
                dismissProgressDialog();
                mEmptyLayout.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_title_left:
                finish();
                break;
            case R.id.commit:
                //TODO 提交记录
                sendCustomPlanFile();
                break;
        }
    }

    @Override
    public void onPictureUploadBegin(String path, String UploadPath) {

    }

    @Override
    public void onPictureUploadFailed(String path, String UploadPath) {

    }

    @Override
    public void onPictureUploadSuccess(String localPath, String smallUrl, String originalUrl) {
        MediaobjectlistBean attachmentBean = new MediaobjectlistBean();
        attachmentBean.setUrl(originalUrl);
        attachmentBean.setType(1);
        mUploadCustomPlanList.get(mCurrentUploadPosition).getmAttachmentView().addAttachment(attachmentBean);
        mDataList.get(mCurrentUploadPosition).setMediaobjectlist(mUploadCustomPlanList.get(mCurrentUploadPosition).getmAttachmentView().getAttachment());
    }

    @Override
    public void onVideoUploadSuccess(String cover, String path) {
        MediaobjectlistBean mediaAttachment = new MediaobjectlistBean();
        mediaAttachment.setUrl(path);
        mediaAttachment.setType(2);
        mUploadCustomPlanList.get(mCurrentUploadPosition).getmAttachmentView().addAttachment(mediaAttachment);
        mDataList.get(mCurrentUploadPosition).setMediaobjectlist(mUploadCustomPlanList.get(mCurrentUploadPosition).getmAttachmentView().getAttachment());
    }


    protected void sendCustomPlanFile() {
        CustomPlanFileUploadRequest customPlanFileUploadRequest = new CustomPlanFileUploadRequest();
        customPlanFileUploadRequest.setCustomplanid(mPlanListBean.getId());
        customPlanFileUploadRequest.setMediaobjectlist(mDataList);

        Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().postDocUpdate(customPlanFileUploadRequest);
        call.enqueue(new Callback<BaseResponse>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                dismissProgressDialog();
                //TODO 通知咨询刷新数字
                Message message = new Message();
                message.what = EventDispatcherEnum.UI_EVENT_CUSTOMEPLANFIEUPLOAD_INFO;
                MFPApplication.getInstance().getEventDispatcher().sendMessage(message);
                finish();
            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {
                dismissProgressDialog();
            }
        });
    }

    @Override
    public String getAttachmentFolder() {
        return "mfp/customplan";
    }


    public class UploadCustomPlanViewHolder {
        private AttachmentView mAttachmentView;
        private TextView mMfEditText;

        public UploadCustomPlanViewHolder(AttachmentView attachmentView, TextView mfEditText) {
            this.mAttachmentView = attachmentView;
            this.mMfEditText = mfEditText;
        }

        public AttachmentView getmAttachmentView() {
            return mAttachmentView;
        }

        public void setmAttachmentView(AttachmentView mAttachmentView) {
            this.mAttachmentView = mAttachmentView;
        }

        public TextView getmMfEditText() {
            return mMfEditText;
        }

        public void setmMfEditText(MfEditText mMfEditText) {
            this.mMfEditText = mMfEditText;
        }
    }

}